package pack

import (
	"fmt"
	jsoniter "github.com/json-iterator/go"
	"mall_frontend_api/biz/model"
	"mall_frontend_api/biz/model/order"
)

func OrderInfo(orderInfo *model.Order, orderItemList []*model.OrdersItem) *order.Order {
	detail := order.NewOrder()
	if orderInfo == nil {
		return detail
	}
	detail.ID = orderInfo.ID
	detail.OrderNumber = orderInfo.OrderNumbers
	detail.SubmitTime = GetTimeUnix(orderInfo.SubmitTime)
	detail.Status = orderInfo.Status
	detail.DeliveryInfo = &order.Delivery{
		Address: fmt.Sprintf("%s %s %s %s", orderInfo.ReceiverProvince, orderInfo.ReceiverCity, orderInfo.ReceiverRegion, orderInfo.ReceiverAddress),
		Name:    orderInfo.ReceiverName,
		Mobile:  orderInfo.ReceiverMobile,
	}
	detail.PaymentTime = GetTimeUnix(orderInfo.PayTime)
	detail.ReceiveTime = GetTimeUnix(orderInfo.ReceiverTime)
	detail.DeliveryTime = GetTimeUnix(orderInfo.DeliveryTime)
	detail.TotalPrice = orderInfo.TotalPrice
	var itemList = make([]*order.OrderItem, 0)
	for _, item := range orderItemList {
		var tmp = order.NewOrderItem()
		tmp.ProductName = item.ProductName
		tmp.ProductNumber = item.ProductNumber
		tmp.ProductPrice = item.Price
		tmp.ProductImage = GetImage(item.ProductIcon)
		var specList = make([]*order.OrderItemProductSpec, 0)
		var orderSpec []*model.OrderItemProductItem
		if err := jsoniter.UnmarshalFromString(item.ProductAttr, &orderSpec); err == nil {
			for _, spec := range orderSpec {
				var t = order.NewOrderItemProductSpec()
				t.Name = spec.Key
				t.Value = spec.Value
				specList = append(specList, t)
			}
		}

		tmp.ProductSpec = specList
		itemList = append(itemList, tmp)
	}
	detail.OrderItemList = itemList
	return detail
}

func OrderList(orderList []*model.Order, orderItemMap map[int64][]*model.OrdersItem) []*order.Order {
	var list = make([]*order.Order, 0)
	if len(orderList) == 0 {
		return list
	}
	for _, m := range orderList {
		if o := OrderInfo(m, orderItemMap[m.ID]); o != nil {
			list = append(list, o)
		}
	}
	return list
}
